package com.yc.pre.config.security;

import com.yc.pre.entity.bean.PreRole;
import com.yc.pre.entity.bo.PermissionRoleBo;
import com.yc.pre.service.PreRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;

/**
 * @author baozhuangyu / ccc-ju@outlook.com
 * @Date 2020/11/30  13:37
 */
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    PreRolePermissionService preRolePermissionService;

    AntPathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 过滤器：用户访问路径时，获取路径所需要的角色
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取用户的访问路径
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        //查询所有路径以及对应角色
        List<PermissionRoleBo> allPermissionWithRole = preRolePermissionService.getAllPermissionWithRole();
        //遍历接口路径是否与请求路径一致，一致则获取对应角色
        for(PermissionRoleBo permissionRoleBo : allPermissionWithRole){
            if(pathMatcher.match(permissionRoleBo.getPermissionUrl(),requestUrl)){
                List<PreRole> roles = permissionRoleBo.getRoles();
                String[] rolesName = roles.stream().filter(role -> !StringUtils.isEmpty(role.getRoleName())).map(PreRole::getRoleName).toArray(String[]::new);
                return SecurityConfig.createList(rolesName);
            }
        }
        //url在数据库不具备角色时，赋予默认角色
        return SecurityConfig.createList("默认角色");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

}
